local skynet 	= require "skynet"
local netpack 	= require "skynet.netpack"
local proto 	= require "proto.proto"
local socket 	= require "socket"
local handler 	= require "char.handler"
local show		= require "showmsg"


local host
local send_request

local CMD = {}
local client = {}		-- {fd  ip  gate watchlog}


-- 消息处理
local function request(name, args, response)
	
	local f = handler[name]

	if not f then 

		show:debug("无效的 %s 消息类型",name)
		return true 
	end 
		
	return f(handler, args, client.fd, response)	
end


-- 消息解包
local function unpack(msg, sz)

	return host:dispatch(msg, sz)	
end 

-- 消息转发
local function dispatch(_, _, type, ...)

	if type == "REQUEST" then

		if request(...) then 

			show.warning("消息处理失败请留意")
		end 				
	else 
		assert(type == "RESPONSE")
		show:debug("暂时不处理 RESPONSE 该消息")
	end 	
end

-- 注册消息类型
if socket:register_protocol("client", skynet.PTYPE_CLIENT, unpack, dispatch) then 
		
	--skynet.call(client.watchdog, "lua", "close", client.fd)
	skynet.exit()
end 


-- 初始化
function CMD.start(conf)

	client = conf
	-- slot 1,2,3,4 set at main.lua
	host, send_request = proto.load(proto.GAME)	
	skynet.call(client.gate, "lua", "forward", client.fd)
	skynet.call(client.gate, "lua", "forward_switch")
	handler:init()
end

-- 关闭连接
function CMD.disconnect()

	-- todo: do something before exit
	skynet.exit()
end

-- 启动服务
skynet.start(function()

	skynet.dispatch("lua", function(_,_, command, ...)
		local f = CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)


end)

